import React from 'react';
import ItemS from '../component/ItemS/ItemS'
import request from '../../utils/request'
import withRouter from './withRouter'
import './Search.less'

class Search extends React.Component {
  state = {
    data: [],
    page: 1,
    keyword: this.props.searchParams.get('keyword'),
  };

  componentDidMount() {
    this.getData();
    addEventListener('scroll', () => {
      // 页面总高
      const scrollHeight = document.documentElement.scrollHeight;
      // 页面显示高度+滚动
      const scrollY = document.documentElement.clientHeight + window.scrollY;
      if (scrollHeight == scrollY) {
        this.changePage()
      }
    })
  };

  componentDidUpdate(prevProps) {
    if (this.props.searchParams.get('keyword') !== prevProps.searchParams.get('keyword')) {
      const keyword = this.props.searchParams.get('keyword') || null;
      this.setState({
        data:[],
        keyword: keyword,
      }, ()=>{
        this.getData()
      })
    }
  }

  // 发送请求获取数据
  getData() {
    // const keyword = this.props.searchParams.get('keyword');
    const url = `https://shop.sunofbeach.net/union/shop/search?page=${this.state.page}&keyword=${this.state.keyword}`;
    request(url).then(({ data }) => {
      this.setState({
        data: this.state.data.concat(data.tbk_dg_material_optional_response.result_list.map_data)
      });
    });
  };

  // 加载下一页
  changePage() {
    this.setState({
      page: this.state.page + 1
    }, () => {
      this.getData();
    });
  };

  render() {
    return (
      <div className='On-sell'>
        {this.state.data.map((item, i) => (
          <ItemS key={i} data={item}></ItemS>
        ))}
      </div>
    )
  };
}

export default withRouter(Search)